package com.outsider.note.service;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.jfinal.weixin.sdk.api.MediaFile;
import com.jfinal.weixin.sdk.msg.in.InVoiceMsg;
import com.outsider.note.dao.VoiceNote;
import com.outsider.note.task.VoiceNoteTimerTask;
import com.outsider.util.Const;
import com.outsider.util.ScheduleUtil;
import com.outsider.util.VoiceApi;
import com.outsider.weixin.dao.User;

public class VoiceNoteService {
	public void longTimeNoteSave(InVoiceMsg inVoiceMsg, Date callDate,String openID) {
		Integer userID=User.dao.findIDbyOpenID(openID);
		String mediaId=inVoiceMsg.getMediaId();
		MediaFile mediaFile=VoiceApi.getVoice(mediaId);
		try {
			String fileName=Const.SDF.format(callDate).replaceAll(":", "")+" "+userID+Const.VOICE_NOTE_FORMAT;
			String filePath=Const.VOICE_NOTE_PATH+File.separator+fileName;
		    File dir=new File(Const.VOICE_NOTE_PATH);
		    if (dir.exists()==false)
		    	dir.mkdirs();
			File f = new File(filePath);
			BufferedOutputStream bof=new BufferedOutputStream(new FileOutputStream(f));
			InputStream in=mediaFile.getFileStream();
			byte[] buff=new byte[1024];
			int len=-1;
			while ((len=in.read(buff))!=-1){
				bof.write(buff, 0, len);
			}
		bof.close();
		in.close();
		
		VoiceNote voiceNote=new VoiceNote();
		voiceNote.setFILEPATH(filePath);
		voiceNote.setDATE(callDate);
		voiceNote.setUserId(userID);
		voiceNote.save();
		ScheduleUtil.getScheduleUtil().addTask(new VoiceNoteTimerTask(voiceNote));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void shortTimeNoteSave(InVoiceMsg inVoiceMsg, Date callDate,String openID) {
		Integer userID=User.dao.findIDbyOpenID(openID);
		VoiceNote voiceNote=new VoiceNote();
		voiceNote.setDATE(callDate);
		voiceNote.setMEDIAID(inVoiceMsg.getMediaId());
		voiceNote.setUserId(userID);
		voiceNote.save();
		ScheduleUtil.getScheduleUtil().addTask(new VoiceNoteTimerTask(voiceNote));
		
	}
	public void deleteVoiceNote(VoiceNote voiceNote){
		ScheduleUtil.getScheduleUtil().deleteTask(voiceNote);
		voiceNote.delete();
		
	}
}
